package com.vitogiovanni.tobook.servlet;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Key;
import com.vitogiovanni.tobook.entity.Locale;
import com.vitogiovanni.tobook.entity.LocaleEndpoint;
import com.vitogiovanni.tobook.entity.Utente;
import com.vitogiovanni.tobook.entity.UtenteEndpoint;

public class InserisciPreferitiServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	/**
     * @see HttpServlet#HttpServlet()
     */
    public InserisciPreferitiServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
				
	}
	
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		UtenteEndpoint utenteEndpoint = new UtenteEndpoint();
		LocaleEndpoint localeEndpoint = new LocaleEndpoint();
		String email = req.getParameter("email");
		String[] locali = req.getParameterValues("localepreferito");
		
		Utente utente = utenteEndpoint.findByEmail(email);
		
		Set<Key> listaLocali = utente.getLocaliPreferiti();
		if(listaLocali == null)
		{
			listaLocali = new HashSet<Key>();
		}
		Locale localeTemp;
		for (String temp : locali) {
			localeTemp = localeEndpoint.findByName(temp);
			if(localeTemp != null)
			{
				listaLocali.add(localeTemp.getId());
			}
		}
		utente.setLocaliPreferiti(listaLocali);
		
		utenteEndpoint.updateUtente(utente);
		
		resp.sendRedirect("/inserimento.html");

		
	}
	
}
